package cn.kmsoft.jssc.controller;

import cn.kmsoft.jssc.entity.analyse.AnalyseTable;
import cn.kmsoft.jssc.entity.analyse.CustomOverlay;
import cn.kmsoft.jssc.entity.analyse.SpatialOverlayParam;
import cn.kmsoft.common.ResInfo;
import cn.kmsoft.wololo.object.query.AnalysisType;
import cn.kmsoft.stgeometry.util.CrsUtil;
import cn.kmsoft.stgeometry.util.GeoJsonQueryUtil;
import cn.kmsoft.stgeometry.util.JTSGeometryWKTUtil;
import cn.kmsoft.stgeometry.util.Shapefile2GeoJson;
import cn.kmsoft.common.utils.StringUtil;
import cn.kmsoft.wololo.object.GeoJson;
import cn.kmsoft.wololo.object.query.GeoJsonQuery;
import cn.kmsoft.wololo.object.query.GeoJsonQuery2;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author : cqwensten
 * @description : todo
 * @email : cqwensten@163.com
 * @date : 2023/5/18
 */

@Component
@RestController
@Api(description = "空间套合查询", tags = "4-Query Controller")
@RequestMapping(value = "/query")
public class QueryController extends BaseController{
    private static final Logger logger = LoggerFactory.getLogger(QueryController.class);
    private final double areaScale = 10000;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss-SSS");


    @ApiOperation(value = "shp2geoJson", notes = "获取默认geoJson对象")
    @RequestMapping(value = "/shp2geoJson", method= RequestMethod.GET)
    public ResInfo shp2geoJson(String shppath){
        ResInfo resInfo = new ResInfo();

        //3-shp2geojson
        //String geoJsonStr = GeoJsonQueryUtil.shp2GeoJsonStr(shppath);
        File shpfile= new File(shppath);
        if(!shpfile.exists()){
            System.out.println(String.format("-->你传入的文件路径： %s 不存在",shppath));
            resInfo.setStatus(ResInfo.FAIL);
            resInfo.setCode(500);
            resInfo.setMsg(String.format("-->你传入的文件路径： %s 不存在",shppath));
            resInfo.setRes(null);

            return resInfo;
        }
        GeoJson geojson= Shapefile2GeoJson.shp2GeoJson(shppath);
        System.out.println();
        System.out.println(geojson);

        resInfo.setStatus(ResInfo.SUCCESS);
        resInfo.setCode(200);
        resInfo.setMsg("shp2GeoJson success! ");
        resInfo.setRes(geojson);

        return resInfo;
    }


    @ApiOperation(value = "shp2geoJsonQuery", notes = "获取默认geoJsonQuery对象")
    @RequestMapping(value = "/shp2geoJsonQuery", method= RequestMethod.GET)
    public ResInfo shp2geoJsonQuery(  String shppath){
        ResInfo resInfo = new ResInfo();

        //3-shp2geoquery
        File shpfile= new File(shppath);
        if( !shpfile.exists()){
            System.out.println(String.format("-->你传入的文件路径： %s 不存在",shppath));
            resInfo.setStatus(ResInfo.FAIL);
            resInfo.setCode(500);
            resInfo.setMsg(String.format("-->你传入的文件路径： %s 不存在",shppath));
            resInfo.setRes(null);

            return resInfo;
        }
        //String geoQueryStr = GeoJsonQueryUtil.shp2GeoQueryStr(shppath, wkid);
        //GeoJsonQuery geoJsonQuery = GeoJsonQueryUtil.shp2GeoQuery(shppath, wkid);
        int wkid = 4524;
        String crsName = JTSGeometryWKTUtil.getShpCrsName(shppath);
        if(!StringUtil.isNullOrEmpty(crsName)){
            try {
                String wkidStr = CrsUtil.getWkidByCrsName(crsName);
                wkid= Integer.parseInt(wkidStr);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        GeoJsonQuery2 geoJsonQuery = GeoJsonQueryUtil.shp2GeoQuery2(shppath, wkid, AnalysisType.SPATIALQUERY);
        System.out.println();
        System.out.println(JSON.toJSONString(geoJsonQuery));

        resInfo.setStatus(ResInfo.SUCCESS);
        resInfo.setCode(200);
        resInfo.setMsg("shp2GeoQuery success! ");
        resInfo.setRes(geoJsonQuery);

        return resInfo;
    }



    @ApiOperation(value = "空间套合查询", notes = "根据analystCode进行空间套合查询。analystCode下可能有多个数据列表，例如输入dltb可实现所有现状的叠加分析")
    @RequestMapping(value = "/spatialQuery", method= RequestMethod.POST)
    public ResInfo spatialQuery(@RequestParam("projectId") String projectId,
                                  @RequestParam("analystCode") String analystCode,
                                  @RequestBody GeoJsonQuery geoJsonQuery ){
        ResInfo resInfo = new ResInfo();

        String jobId = UUID.randomUUID().toString();
        //1、解析跨域请求的参数
        if( geoJsonQuery == null || geoJsonQuery.getGeoJson() == null) {
            //无图形，叠加终止
            resInfo.setMsg("无图形，空间查询终止");
            resInfo.setStatus(ResInfo.FAIL);
            return resInfo;
        }
        int wkid = geoJsonQuery.getWkid();
        //2、根据analyst获取不同的数据项图层表名
        List<AnalyseTable> analyseTables = this.getAnalyseTablesByAnalystCode(this.analyseConfig, analystCode);

        //3、SpatialOverlayParam
        SpatialOverlayParam customParam =  new SpatialOverlayParam();
        customParam.setAnalyseTables(analyseTables);
        customParam.setTaskId(jobId);
        customParam.setGeoJsonQuery(geoJsonQuery);
        customParam.setPhase(sdf.format(new Date()).toString());

        //4、执行
        List<CustomOverlay> cusOverlayList = this.doOverlayAnalyst(projectId, customParam);
        if(cusOverlayList != null && cusOverlayList.size()>0 ) {
            resInfo.setStatus(ResInfo.SUCCESS);
            resInfo.setCode(200);
            resInfo.setMsg("空间套合查询完成");
            resInfo.setRes(cusOverlayList);
        }else {
            resInfo.setStatus(ResInfo.FAIL);
            resInfo.setCode(500);
            resInfo.setMsg("空间套合查询失败");
            resInfo.setRes(projectId);
        }

        return resInfo;
    }



    @ApiOperation(value = "空间套合查询1", notes = "根据analystCode和yearStr进行空间套合查询，一般情况下analystCode和yearStr会锁定在一个图层数据。analystCode列表可通过相关接口获取")
    @RequestMapping(value = "/spatialQuery1", method= RequestMethod.POST)
    public ResInfo spatialQuery1(@RequestParam("projectId") String projectId,
                                   @RequestParam("analystCode") String analystCode,
                                   @RequestParam("yearStr") String yearStr,
                                   @RequestBody GeoJsonQuery geoJsonQuery ){
        ResInfo resInfo = new ResInfo();

        String jobId = UUID.randomUUID().toString();
        //1、解析跨域请求的参数
        if( geoJsonQuery == null || geoJsonQuery.getGeoJson() == null) {
            //无图形，叠加终止
            resInfo.setMsg("无图形，空间查询终止");
            resInfo.setStatus(ResInfo.FAIL);
            return resInfo;
        }
        //2、根据analystCode和yearStr获取对应的数据项图层表名
        List<AnalyseTable> analyseTables = this.getAnalyseTableByAnalystCodeAndYear(this.analyseConfig, analystCode,yearStr);

        //3、SpatialOverlayParam
        SpatialOverlayParam customParam =  new SpatialOverlayParam();
        customParam.setAnalyseTables(analyseTables);
        customParam.setTaskId(jobId);
        customParam.setGeoJsonQuery(geoJsonQuery);
        customParam.setPhase(sdf.format(new Date()).toString());

        //4、执行
        List<CustomOverlay> cusOverlayList = this.doOverlayAnalyst(projectId, customParam);
        if(cusOverlayList != null && cusOverlayList.size()>0 ) {
            resInfo.setStatus(ResInfo.SUCCESS);
            resInfo.setCode(200);
            resInfo.setMsg("空间查询完成");
            resInfo.setRes(cusOverlayList);
        }else {
            resInfo.setStatus(ResInfo.FAIL);
            resInfo.setCode(500);
            resInfo.setMsg("空间查询失败");
            resInfo.setRes(projectId);
        }

        return resInfo;
    }




}
